<?php

namespace App\Web\Model;

use App\Customer\Model\CaseModel;
use App\Service\ExternalAPI\EhireApi;
use App\Customer\Model\UserAuth as UserAuth;
use EchoPHP\Facades\Db;
use EchoPHP\Facades\Log;

/**
 * Class EhireUser
 * 网才用户相关业务逻辑
 * @package App\Web\Model
 */
class EhireUser extends Model {

    /**登录网才接口
     * @param $memberName
     * @param $userName
     * @param $passWord
     * @return array|mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function login($memberName, $userName, $passWord, $allowmultilogin = 0) {
        $ehireApi = new EhireApi();
        $resultBody = $ehireApi->login($memberName, $userName, $passWord, $allowmultilogin);
        if ($resultBody['code'] != '00000') {
            return $resultBody;
        }

        $resultBody['data']['logintime'] = time();
        $resultBody['data']['username'] = $userName;

        //查询网才账号管理员表。 超级管理员不可修改角色和删除。
        $sql = 'select role,`status` from EhireUser where hruid=? and status in ( ?, ? )';
        $var = [$resultBody['data']['hruid'], '01', '05'];
        $userInfo = Db::selectOne($sql, $var);
        //增加锁定查询
        if ($userInfo['status'] == '05') {
            return array(
                'code' => '50001', //账户锁定code
                'msg' => "您的账户已被锁定，如要解锁请联系管理员！"
            );
        }
        $resultBody['data']['role'] = 9; //1:超级管理员；2-管理员；9-普通人员；后续通过数据库来赋值，暂时这样测试
        if (isset($userInfo['role'])) {
            $resultBody['data']['role'] = $userInfo['role'];
        }

        if (isset($userInfo['status'])) {
            $resultBody['data']['status'] = $userInfo['status'];
            $info = "";
            switch ( $userInfo['status']) {
                case '01':
                    $info = "正常";
                    break;
                case '05':
                    $info = "锁定";
                    break;
            }
            $resultBody['data']['statusinfo'] = $info;
        }


        //查询网才账号RPO客户联系人绑定关系表。
        $sql = 'select id from CustomerAccount where ehireaccid=? and status=? order by id desc';
        $var = [$resultBody['data']['hruid'], '01'];
        $customerInfo = Db::select($sql, $var);
        $resultBody['data']['ctrpoid'] = '';
        foreach ($customerInfo as $item) {
            $resultBody['data']['ctrpoid'] .= ',' . $item['id'];
        }
        $resultBody['data']['ctrpoid'] = trim($resultBody['data']['ctrpoid'], ',');


        //获取交易公司
        $caseModel = new CaseModel();
        $subCaseData = $caseModel->getSubCaseInfo($resultBody['data']['hruid']);
        $subData = $subCaseData['sublist'];
        //将suibid存入jwt token中
        $resultBody['data']['subids'] = array_column($subData, 'subid');
        $userAuth = new UserAuth();
        $resultBody['data']['authToken'] = $userAuth->setLoginSession($resultBody['data']['hruid'], $resultBody['data']);
        unset($resultBody['data']['subids']);
        $resultBody['data']['sublist'] = $subData;
        return $resultBody;
    }

    /**
     * @param $ctmid
     * @param array $hruid
     * @return array|null
     */
    public function getList($ctmid, $hruid = []) {
        if (empty($ctmid)) {
            return null;
        }

        $field = 'ctmid,hruid,role,createdate,updatedate,status';
        $sql = 'SELECT ' . $field . ' FROM EhireUser WHERE ctmid =? ';

        $var = [$ctmid];
        if (!empty($hruid)) {
            $this->arrValueToKey($hruid);
            $inFlag = $this->arrAppand($var, $hruid);
            $sql .= ' and hruid in (' . $inFlag . ')';
        }

        $list = Db::select($sql, $var);

        return $list;
    }


    /**增加超级管理员
     * @param $ctmid
     * @param $hruid
     * @param $role
     * @param $creatorHruid
     * @return array
     */
    public function addSuperUser($ctmid, $hruid, $role, $creatorHruid) {
        $result = ['status' => false, 'message' => '保存失败'];
        if (empty($ctmid) || empty($hruid) || !in_array($role, [1, 2]) || $creatorHruid < 0) {
            $result['message'] = '参数异常';
            return $result;
        }
        try {
            //获取ctmid是否有账号数据
            $sql = 'SELECT role,status FROM EhireUser WHERE ctmid =? and hruid =?';
            $var = [$ctmid, $hruid];
            $list = Db::selectOne($sql, $var);

            //账号有效，则直接返回成功
            if (!empty($list) && isset($list['status']) && $list['status'] == '01' && $list['role'] == 1) {
                $result['status'] = true;
                $result['message'] = '保存成功';
                return $result;
            }

            //账号存在，但数据不是超级管理员或无效，则更新数据
            if (!empty($list) && isset($list['status'])) {
                $updateSql = 'update EhireUser set role=?, creatorhruid=?, updatorhruid=?, status=?, createdate=Now(),updatedate=Now() where ctmid=? and hruid=?';
                $updateVar = [
                    $role,
                    0,
                    0,
                    '01',
                    $ctmid,
                    $hruid
                ];
                $upResult = Db::update($updateSql, $updateVar);
                if (!$upResult) {
                    return $result;
                }
                $result['status'] = true;
                $result['message'] = '保存成功';
                return $result;
            }

            //不存在，则新增数据
            $sql = 'INSERT INTO EhireUser(ctmid,hruid,role,status,creatorhruid,updatorhruid,createdate,updatedate)';
            $sql .= 'VALUES(?,?,?,?,?,?,Now(),Now())';
            $var = [$ctmid, $hruid, $role, '01', $creatorHruid, $creatorHruid];
            $saveResult = Db::insert($sql, $var);
            if (!$saveResult) {
                return $result;
            }
        } catch (\Exception $e) {
            return $result;
        }

        $result['status'] = true;
        $result['message'] = '保存成功';
        return $result;
    }

    /**新增非超级管理员用户
     * @param $accessKey
     * @param $role
     * @param $userName
     * @param $name
     * @param $email
     * @param $myhruid
     * @param $myCtmId
     * @return array|mixed|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function addUser($accessKey, $role, $userName, $name, $email, $myhruid, $myCtmId) {
        $oprRole = $this->getEhireRole($myhruid);
        if (!in_array($oprRole, [1, 2])) {
            $resultBody = [
                'code' => 99999,
                'msg' => '无权限进行操作',
                'data' => []
            ];
            return $resultBody;
        }
        if ($role != 9 && $oprRole == 2) {
            $resultBody = [
                'code' => 99999,
                'msg' => '新增用户角色只能是普通用户',
                'data' => []
            ];

            return $resultBody;
        }
        if (!in_array($role, [2, 9])) {
            $resultBody = [
                'code' => 99999,
                'msg' => '新增用户角色只能是管理员或普通用户',
                'data' => []
            ];

            return $resultBody;
        }
        $ehireApi = new EhireApi();
        $resultBody = $ehireApi->addUser($accessKey, $userName, $name, $email);
        //新增管理员时保存到ehireuser表里，普通用户不用管
        if ($resultBody['code'] == '00000') {
            $hrUid = $resultBody['data']['hruid'];
            $result = $this->updateUserRole($role, $hrUid, $myhruid, $myCtmId);
        }
        return $resultBody;
    }

    /**
     * 更新用户角色信息时，对应更改EhireUser表中用户信息
     * @param $role
     * @param $hrUid
     * @param $myHrUid
     * @return bool|int
     */
    public function updateUserRole($role, $hrUid, $myHrUid, $myCtmId) {
        $addResult = 1;
        if ($role == 2 || $role == 9) {
            //设置为管理员
            $sql = 'select hruid,role,status from EhireUser where hruid=?';
            $var = [$hrUid];
            $result = Db::selectOne($sql, $var);
            if (empty($result)) {
                //若表里没有此人，则插入数据
                $insertSql = 'insert into EhireUser (hruid,ctmid,role,creatorhruid,updatorhruid,status,createdate,updatedate) 
                    values (?,?,?,?,?,?,Now(),Now())';
                $insertVar = [
                    $hrUid,
                    $myCtmId,
                    $role,
                    $myHrUid,
                    $myHrUid,
                    '01',
                ];
                $addResult = Db::insert($insertSql, $insertVar);
            } else {
                //表里已存在此人
                if ($result['status'] != '01' || $result['role'] != $role) {
                    $updateSql = 'update EhireUser set role=?, updatorhruid=?, status=?, updatedate=Now() where hruid=?';
                    $updateVar = [
                        $role,
                        $myHrUid,
                        '01',
                        $hrUid
                    ];
                    $addResult = Db::update($updateSql, $updateVar);
                }
            }
        }
        if (!$addResult) {
            Log::error('编辑用户角色时修改EhireUser表失败,hruid:' . $hrUid);
        }
        return $addResult;
    }

    /**
     * 删除用户
     * @param $accessKey
     * @param $hruids
     * @return array|mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function deleteUsers($accessKey, $hruids, $myHrUid) {
        $oprRole = $this->getEhireRole($myHrUid);
        if (!in_array($oprRole, [1, 2])) {
            $resultBody = [
                'code' => 99999,
                'msg' => '无权限进行操作',
                'data' => []
            ];
            return $resultBody;
        }
        $hruidsArr = explode(',', $hruids);
        if (count($hruidsArr) > 50) {
            $resultBody = [
                'code' => 99999,
                'msg' => '最多一次可删除50个',
                'data' => []
            ];
            return $resultBody;
        }
        if (in_array($myHrUid, $hruidsArr)) {
            $resultBody = [
                'code' => 99999,
                'msg' => '不可删除自己',
                'data' => []
            ];
            return $resultBody;
        }
        //超级管理员不能删除
        //超级管理员能删除管理员和普通用户 管理员能删除普通用户
        $inFlag = substr(str_repeat('? ,', (count($hruidsArr))), 0, -1);
        $sql = 'select hruid,role from EhireUser where hruid in (' . $inFlag . ') and (role=? or role=?) and status=?';
        $var = array_merge($hruidsArr, [1, 2, '01']);
        $admins = Db::select($sql, $var);
        if (!empty($admins)) {
            $userListWithRole = [];//用户列表 role作为键值

            foreach ($admins as $admin) {
                $userListWithRole[$admin['role']] = $admin['hruid'];
            }

            if (!empty($userListWithRole[1])) {
                return [
                    'code' => 99999,
                    'msg' => '不可删除超级管理员',
                    'data' => []
                ];
            }
            if (!empty($userListWithRole[2]) && $oprRole == 2) {
                return [
                    'code' => 99999,
                    'msg' => '不可删除管理员',
                    'data' => []
                ];
            }
        }
        $ehireApi = new EhireApi();
        $resultBody = $ehireApi->deleteUsers($accessKey, $hruids);
        //删除成功时，如果被删除的用户在EhireUser中，则删除这些用户
        if ($resultBody['code'] == '00000') {
            $deleteUserArr = explode(',', $resultBody['data']['successhruids']);
            $inFlag = substr(str_repeat('? ,', (count($deleteUserArr))), 0, -1);
            $deleteSql = 'update EhireUser set status=? where hruid in (' . $inFlag . ')';
            $deleteVar = array_merge(['06'], $deleteUserArr);
            $deleteResult = Db::update($deleteSql, $deleteVar);

            //将被删除用户的loginsession清理掉   @2020.7.6 去除redis存储逻辑 防止以后再用 代码片暂时保留
//            $userAuth = new UserAuth();
//            foreach ($deleteUserArr as $deleteUser) {
//                $userAuth->delLoginSession($deleteUser);
//            }
            //清理用户的绑定信息
            $sql = 'update CustomerAccount set updator = ?, bindehire = ?,binduid = ? ,ehireaccid = null ,ehirectmid=null,updatedate = NOW(),binddate = Now()
        where ehireaccid in (' . $inFlag . ')';
            $var = array_merge([0, 0, 0], $deleteUserArr);
            $result = Db::update($sql, $var);
            if (!$result) {
                Log::error('绑定信息清理失败,hruids:' . $resultBody['data']['successhruids']);
            }
        }
        return $resultBody;
    }

    /**
     * 更新用户信息
     * @param $accessKey
     * @param $role
     * @param $hrUid
     * @param $email
     * @param $userName
     * @param $name
     * @param $myhruid
     * @param $myCtmId
     * @return mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function updateUserInfo($accessKey, $role, $hrUid, $email, $userName, $name, $myhruid, $myCtmId) {
        if (isset($role) && !empty($role)) {
            $oprRole = $this->getEhireRole($myhruid);
            if (!in_array($oprRole, [1, 2]) && $hrUid != $myhruid) {
                $resultBody = [
                    'code' => 99999,
                    'msg' => '无权限进行操作',
                    'data' => []
                ];
                return $resultBody;
            }
            $userRole = $this->getEhireRole($hrUid);
            if ($oprRole == 2 && $userRole != 9) {
                $resultBody = [
                    'code' => 99999,
                    'msg' => '您无权修改该用户',
                    'data' => []
                ];
                return $resultBody;
            }

            //如果是超级管理员不给修改角色
            $sql = 'select role from EhireUser where hruid=? and status=?';
            $var = [$hrUid, '01'];
            $result = Db::selectOne($sql, $var);
            if (empty($result)) {
                $userRole = 9;
            } else {
                $userRole = $result['role'];
            }

            if ($userRole == 1 && $role != 1) {
                $resultBody = [
                    'code' => 99999,
                    'msg' => '超级管理员角色不可修改',
                    'data' => []
                ];
                return $this->json($resultBody);
            }
            if (!in_array($role, [2, 9])) {
                $resultBody = [
                    'code' => 99999,
                    'msg' => '用户角色只能修改为管理员或普通用户',
                    'data' => []
                ];
                return $resultBody;
            }
        }

        $ehireApi = new EhireApi();
        $resultBody = $ehireApi->updateUserInfo($accessKey, $email, $hrUid, $userName, $name);
        if ($resultBody['code'] == '00000' && isset($role) && !empty($role)) {
            //当角色更新为管理员时 查看ehireuser 有则更新，无则插入
            $this->updateUserRole($role, $hrUid, $myhruid, $myCtmId);
        }
        return $resultBody;
    }

    /**
     * 添加已有用户
     * @param $accessKey
     * @param $hrUid
     * @param $role
     * @param $myhruid
     * @param $myCtmId
     * @return array|mixed|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function addExistUser($accessKey, $hrUid, $role, $myhruid, $myCtmId) {
        $oprRole = $this->getEhireRole($myhruid);
        if (!in_array($oprRole, [1, 2])) {
            $resultBody = [
                'code' => 99999,
                'msg' => '无权限进行操作',
                'data' => []
            ];
            return $resultBody;
        }
        $ehireApi = new EhireApi();
        $resultBody = $ehireApi->addExistUser($accessKey, $hrUid);
        if ($resultBody['code'] == '00000') {
            $result = $this->updateUserRole($role, $hrUid, $myhruid, $myCtmId);
        }
        return $resultBody;
    }

    /**
     * 获取用户列表
     * @param $accessKey
     * @param $pageIndex
     * @param $pageSize
     * @param $sort
     * @param $whereString
     * @return array|mixed|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getUserList($accessKey, $pageIndex, $pageSize, $sort, $whereString, $myHrUid, $ctmId) {
        $oprRole = $this->getEhireRole($myHrUid);
        if (!in_array($oprRole, [1, 2])) {
            $resultBody = [
                'code' => 99999,
                'msg' => '无权限进行操作',
                'data' => []
            ];
            return $resultBody;
        }
        $ehireApi = new EhireApi();
        $resultBody = $ehireApi->getUserList($accessKey, $pageIndex, $pageSize, $sort, $whereString);
        if ($resultBody['code'] == '00000' && !empty($resultBody['data']['userlist'])) {
            $userList = $this->getUserAccountInfo($ctmId, $resultBody['data']['userlist']);
            $resultBody['data']['userlist'] = $userList;
        }
        return $resultBody;
    }

    /**
     * 获取用户列表 无需登录
     * @param $accessKey
     * @param $pageIndex
     * @param $pageSize
     * @param $sort
     * @param $whereString
     * @return array|mixed|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getUserListWithNoToken($ctmId, $pageIndex, $pageSize, $sort, $whereString) {
        //获取操作人角色信息
        $ehireApi = new EhireApi();
        $resultBody = $ehireApi->getUserList2($ctmId, $pageIndex, $pageSize, $sort, $whereString);
        if ($resultBody['code'] == '00000' && !empty($resultBody['data']['userlist'])) {
            $userList = $this->getUserAccountInfo($ctmId, $resultBody['data']['userlist']);
            $resultBody['data']['userlist'] = $userList;
        }
        return $resultBody;
    }

    /**
     * 通过hruid获取用户角色信息
     * @param $hrUid
     * @return int
     */
    public function getEhireRole($hrUid) {
        $sql = 'select role from EhireUser where hruid = ? and status = ?';
        $var = [$hrUid, '01'];
        $result = Db::selectOne($sql, $var);
        if (empty($result)) {
            return 9;
        }
        return $result['role'];
    }

    /**
     * 用户信息列表拼接获取用户联系人信息
     * @param $userList
     * @return mixed
     */
    public function getUserAccountInfo($ctmId, $userList) {
        $userHruids = array_column($userList, 'hruid');
        //拼接用户角色
        $inFlag = substr(str_repeat('? ,', (count($userHruids))), 0, -1);
        $sql = 'select hruid,role,ctmid,`status` from EhireUser where hruid in (' . $inFlag . ') and status in ( ?, ?)';
        $var = array_merge($userHruids, ['01','05']);
        $userInfo = Db::select($sql, $var);
        $userInfo = array_column($userInfo, null, 'hruid');

        //拼接联系人信息
        $sql = 'select DISTINCT ehireaccid from CustomerAccount where ehireaccid in (' . $inFlag . ') and bindehire =1 and status=?';
        $var = array_merge($userHruids, ['01']);
        $userAccount = Db::select($sql, $var);
        $userAccount = array_column($userAccount, null, 'ehireaccid');
        foreach ($userList as &$user) {
            $user['role'] = isset($userInfo[$user['hruid']]['role']) ? (int)$userInfo[$user['hruid']]['role'] : 9;
            $user['ctmid'] = $ctmId;
            $user['status'] = isset($userInfo[$user['hruid']]['status']) ? $userInfo[$user['hruid']]['status'] : 0;
            $user['createtime'] = !empty($user['createtime']) ? date("Y-m-d H:i", strtotime($user['createtime'])) : '';
            $user['logintime'] = !empty($user['logintime']) ? date("Y-m-d H:i", strtotime($user['logintime'])) : '';
            switch ($user['role']) {
                case 1:
                    $user['rolename'] = '超级管理员';
                    break;
                case 2:
                    $user['rolename'] = '管理员';
                    break;
                case 9:
                    $user['rolename'] = '普通用户';
                    break;
                default:
                    break;
            }
            if (isset($userAccount[$user['hruid']])) {
                $user['isbind'] = 1;
            } else {
                $user['isbind'] = 0;
            }

            $info = "";
            switch ($user['status']) {
                case '01':
                    $info = "正常";
                    break;
                case '05':
                    $info = "锁定";
                    break;
            }
            $user['statusinfo'] = $info;

        }
        unset($user);
        return $userList;
    }

    /**
     * Notes:客户联系人解绑
     * @param $userId
     * @param $subId
     * @param $accountId
     * @return array
     */
    public function unbindUser($userId, $subId, $accountId) {
        $sql = 'update CustomerAccount set bindehire = ?,ehireaccid=null,ehirectmid=null,binddate = Now(),updatedate=Now(),binduid = ? 
                where subid = ? and id = ?';
        $var = [0, $userId, $subId, $accountId];
        $result = Db::update($sql, $var);
        if (!$result) {
            return [
                'code' => '99999',
                'msg' => '操作失败',
                'data' => []
            ];
        } else {
            return [
                'code' => '00000',
                'msg' => '操作成功',
                'data' => []
            ];
        }

    }

    /**
     * Notes:客户联系人绑定用户
     * @param $subId
     * @param $userId
     * @param $accountId
     * @param $ctmId
     * @param $hrUid
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function bindUser($subId, $userId, $accountId, $ctmId, $hrUid) {
        if (empty($accountId) || empty($hrUid) || empty($subId) || empty($ctmId)) {
            return [
                'code' => '99999',
                'msg' => '参数错误',
                'data' => []
            ];
        }
        //判断该用户是否已被绑定过
        $sql = 'select id,ehireaccid from CustomerAccount where subid = ? and status = ? and bindehire = ?';
        $var = [$subId, '01', 1];
        $result = Db::select($sql, $var);
        if (in_array($accountId, array_column($result, 'id'))){
            return [
                'code' => '99999',
                'msg' => '该用户已绑定',
                'data' => []
            ];
        }
        if (in_array($hrUid, array_column($result, 'ehireaccid'))){
            return [
                'code' => '99999',
                'msg' => '此网才账号已绑定客户下另一联系人',
                'data' => []
            ];
        }

        $ehireApi = new EhireApi();
        $where = 'hruids|' . $hrUid;
        $checkExist = $ehireApi->getUserList2($ctmId, null, null, null, $where);
        if ($checkExist['code'] != '00000' || empty($checkExist['data']['userlist'])) {
            return [
                'code' => '99999',
                'msg' => '用户不存在',
                'data' => []
            ];
        }

        //未绑定时进行绑定
        $updateSql = 'update CustomerAccount set bindehire=?,ehirectmid=?,ehireaccid=?,binduid=?,binddate=Now(),updatedate=Now() where subid = ? and id = ? and status = ?';
        $updateVar = [1, $ctmId, $hrUid, $userId, $subId, $accountId, '01'];
        $updateResult = Db::update($updateSql, $updateVar);
        if ($updateResult) {
            return [
                'code' => '00000',
                'msg' => '绑定成功',
                'data' => []
            ];
        } else {
            return [
                'code' => '99999',
                'msg' => '绑定失败',
                'data' => []
            ];
        }
    }

    /**
     * 锁定和解锁用户
     * @param $role
     * @param $hrUid
     * @param $myhruid
     * @param $myCtmid
     * @param $ctmid
     * @param $type
     * @return array
     */
    public function managerUser($role, $hrUid, $myhruid,$myCtmid,$ctmid, $type) {
        $oprRole = $this->getEhireRole($myhruid);
        if (!in_array($oprRole, [1, 2]) && $hrUid != $myhruid && $myCtmid != $ctmid) {
            $resultBody = [
                'code' => 99999,
                'msg' => '无权限进行操作',
                'data' => []
            ];
            return $resultBody;
        }
        $userRole = $this->getEhireRole($hrUid);
        if ($oprRole == 2 && $userRole != 9) {
            $resultBody = [
                'code' => 99999,
                'msg' => '您无权修改该用户',
                'data' => []
            ];
            return $resultBody;
        }

        //如果是超级管理员不给修改角色
        $sql = 'select role from EhireUser where hruid=? and status=?';
        $var = [$hrUid, '01'];
        $result = Db::selectOne($sql, $var);
        if (empty($result)) {
            $userRole = 9;
        } else {
            $userRole = $result['role'];
        }

        if ($userRole == 1 && $role != 1) {
            $resultBody = [
                'code' => 99999,
                'msg' => '超级管理员角色不可修改',
                'data' => []
            ];
            return $this->json($resultBody);
        }
        if (!in_array($role, [2, 9])) {
            $resultBody = [
                'code' => 99999,
                'msg' => '用户角色只能修改为管理员或普通用户',
                'data' => []
            ];
            return $resultBody;
        }

        $sql = "UPDATE EhireUser set `status` = ? , updatorhruid = ? where hruid = ?";
        $message = '';
        $status = '01';
        switch ($type) {
            case 1 :
                $status = '05';
                $message = "锁定";
                break;
            case 2:
                $status = '01';
                $message = "解锁";
                break;
        }
        $updateVar = [$status,$myhruid,$hrUid];
        $updateResult = Db::update($sql, $updateVar);

        if ($updateResult) {
            return [
                'code' => '00000',
                'msg' => $message . '成功',
                'data' => []
            ];
        } else {
            return [
                'code' => '99999',
                'msg' => $message . '失败',
                'data' => []
            ];
        }
    }
}